<?php
namespace app\api\controller;

use app\api\common\controller\Api;
use think\facade\Db;
// use app\api\common\controller\MidOrder;
use app\api\model\Order as modelOrder;
use app\api\common\controller\PriceSystem;


/**
 * @Apidoc\Title("Demo.php")
 * @Apidoc\Group("api")
 */
class Cart extends Api
{
	public function _structure(){
        // $this->user_member_id=13757;
        if($this->user_member_id == 0){
        	$this->result('请先登录',[],400);
        }
    }
	   // 加购物车
     public function makeCart(){
         $post = $this->request::param();
         $post['number']=$post['number']?$post['number']:1;
          $rule = [
                // 'users|游客信息'=>'require',
                // 'name|姓名' => 'require',
                // 'tel|联系电话'  => 'require|number|mobile',
                // 'use_time|入园日期'=>'require',
            ];

         if($post['server_type']==1){
                $ticket_price=Db::name('ticket_price')->where('tree_ticket_id',$post['server_id'])->field('activity_price,price')->find();
                $price=$ticket_price['price'];
                $activity_price=$ticket_price['activity_price'];
                $post['use_time']=strtotime(date('Y')."-".$post['use_time']);

         }elseif($post['server_type']==2){
            // $post['spec_item']=time().",1";
                $lease=Db::name('lease')->where('id',$post['server_id'])->find();
               $server_id=$post['server_id'];
               if($lease['spec_type']=="more"){
                    if(isset($post['house_id']) && $post['house_id']>0){
                            $post['house_num']=$post['house_id'];
                            $post['house_title']=Db::name('house')->where('id',$post['house_id'])->value('title');
                    }
                    
                    $spec_id=$post['spec_item'];
                    $spec_id=explode(',',$post['spec_item']);
                    sort($spec_id);
                    if(count($spec_id)==1){
                            $time_id=$spec_id[0];
                            $where_price=[
                                ['lease_id','=',$post['server_id']],
                               
                                ['sku_val','like','%'.$time_id.'%']
                            ];
                            if($post['server_id']==1){
                                array_push($where,  ['day_time','=',date('w',time())]);
                            }
                            $post['use_time']=$spec_id[0]>200?$spec_id[0]:time();
                    }else{

                        $sku_val=[$spec_id[0]];
                        $time_id=$spec_id[0];
                       if($post['server_id']==1){
                            $time_end=Db::name('spec_item')->where('spec_id',2)->where('item',date('w',$spec_id[1]))->fetchsql(false)->value('id');
                            array_push($sku_val, $time_end);
                        }
                        
                        sort($sku_val);
                        $sku_val=implode('_',$sku_val);
                        $where_price=[
                            ['lease_id','=',$post['server_id']],
                           
                            ['sku_val','=',$sku_val]
                        ];
                        if($post['server_id']==1){
                            array_push($where_price, ['day_time','=',date('w',$spec_id[1])]);
                        }
                        $post['use_time']=$spec_id[1];
                    }
                    $lease_price=Db::name('lease_price')->where($where_price)->fetchsql(false)->find();
                
                    $price=$lease_price['price'];
                    $activity_price=$lease_price['activity_price'];
                    $post['time_id']=$time_id;

               }else{
                  $price=$lease['price'];
                  $activity_price=$lease['activity_price'];
               }

         }elseif($post['server_type']==3){//商品加入购物车
            
                $goods=Db::name('goods')->where('products_id',$post['server_id'])->find();
                if($goods['spec_type']=="more"){
                    $spec_item=$post['spec_item'];
                    $spec_item=explode('_',$spec_item);
                    sort($spec_item);
                    $spec_item=implode('_',$spec_item);
                    $goods_value=Db::name('goods_value')->where('products_id',$post['server_id'])->where('sku_val',$spec_item)->find();
                    if($goods_value){
                         $price=$goods_value['price'];
                         $activity_price=$goods_value['activity_price'];
                    }else{
                         $price=$goods['price'];
                         $activity_price=$goods['activity_price'];
                    }
                    
                    $post['spec']=$spec_item;
                }else{
                     $price=$goods['price'];
                     $activity_price=$goods['activity_price'];
                }
         }
            $post['members_id']=$this->user_member_id;
            $post['price']=$price;
            $post['activity_price']=$activity_price;

            $msg=$this->validate($post, $rule);
            if($msg!==true) $this->result($msg, [],403,'json');
            $where=[
                ['server_id','=',$post['server_id']],
                ['type','=',$post['server_type']],
                ['members_id','=',$this->user_member_id]
            ];
            $post['type']=$post['server_type'];
            if($post['server_type']==2 && $post['server_id']==1){
                $temp_time=strtotime(date('Y-m-d',$post['use_time']));
                $post['use_time']=$temp_time;
                array_push($where, ['house_num','=',$post['house_id']]);
                array_push($where, ['time_id','=',$time_id]);
                array_push($where, ['use_time','=',$temp_time]);
                $cart=Db::name('cart')->where($where)->fetchsql(false)->find();
                $itps_itme=Db::name('spec_item')->where('id',$time_id)->value('item');
                if($cart)$this->result($post['house_title']."树屋".date('Y-m-d',$post['use_time']).$itps_itme."已加入购物车请勿重复操作", [],403,'json');
            }elseif($post['server_type']==2 && $post['server_id']==11){
                array_push($where, ['time_id','=',$time_id]);
                $cart=Db::name('cart')->where($where)->fetchsql(false)->find();
                $itps_itme=Db::name('spec_item')->where('id',$time_id)->value('item');
                if($cart)$this->result($itps_itme."已加入购物车请勿重复操作", [],403,'json');
            }else{
               $cart=Db::name('cart')->where($where)->fetchsql(false)->find(); 
            }
            
        try{
          if($cart){
                $res=Db::name('cart')->where(['id'=>$cart['id']])->update(['number'=>$post['number']+$cart['number']]);
          }else{
            $res=Db::name('cart')->strict(false)->insert($post);
          }
            if($res){
                     $this->result('加入购物车成功', [],200,'json');
            }else{
                 $this->result('加入购物车失败', [],403,'json');
            }
          
        }catch(Exception $e){
            $this->result($e->getMessage(), [],403,'json');
        }
            
     }
     // 购物车列表
	   public function getCartList(){
          $post=Db::name('cart')->where('members_id',$this->user_member_id)->select()->toArray();
          foreach ($post as $k => $v) {
            $users=Db::name('user')->whereIn('member_id',$v['members_id'])->find();
            $post[$k]['name']=$users['name'];
            $post[$k]['tel']=$users['phone'];
            $unit='';
            $spec_item='';
            $amount=0;
            switch ($v['type']) {
                case 1://票
                   $ticket=Db::name('ticket')->where('id',$v['server_id'])->find();
                   $ticket_price=Db::name('ticket_price')->where('tree_ticket_id',$v['server_id'])->whereDay('create_time')->find();
              
                   $title=$ticket['title'];
                   $image=$ticket['thumb'];
                   $post[$k]['price']=$ticket_price['price'];
                   $post[$k]['activity_price']=$ticket_price['activity_price'];
                    break;
                case 2:
                    $lease=Db::name('lease')->where('id',$v['server_id'])->find();
                    $amount=$lease['deposit'];
                    $title=$lease['title'];
                    $image=$lease['thumb'];
                    $unit=$lease['unit'];
                   break;
                case 3:
                    $goods=Db::name('goods')->where('products_id',$v['server_id'])->find();
                    $title=$goods['products_title'];
                    $image=$goods['cover_picture'];
                    $spec_item=Db::name('goods_value')->where('products_id',$v['server_id'])->where('sku_val',$v['spec'])->value('sku');
                   break;
            }
            $timeZone='';
            if($v['type']==2 && $v['server_id']==1 && !empty($v['use_time'])){
                $timeZone=Db::name('spec_item')->where('id',$v['time_id'])->fetchsql(false)->value('item');
                  
            }elseif($v['type']==2 && $v['server_id']==11){
                 $timeZone=Db::name('spec_item')->where('id',$v['time_id'])->fetchsql(false)->value('item');
            }
             $post[$k]['use_time']=$v['use_time']?date('Y-m-d',$v['use_time']):"";
             $post[$k]['timeZone']=$timeZone;  
             $post[$k]['checked']=false;
             $post[$k]['amount']=$amount;
             $post[$k]['image']=$image;
             $post[$k]['title']=$title;
             $post[$k]['unit']=$unit;
             $post[$k]['spec_item']=$spec_item;
          }
          $this->result('',['lists'=>$post,'number'=>count($post)],200,'json');   
       }
       //修改购物车里的数量
       public function cartNumUpdate(){
          $cart_ids=input('cart_ids');
          $number=input('number');
          $res=Db::name('cart')->where('id',$cart_ids)->update(['number'=>$number]);
          if($res) $this->result('数量修改成功', [],200,'json'); 
          $this->result('数量修改失败', [],403,'json'); 
       }
       public function delCart(){
          $cart_ids=input('cart_ids');
          $where=[
            ['members_id','=',$this->user_member_id],
            ['id','in',$cart_ids]
          ];
          $res=Db::name('cart')->where($where)->delete();
          if($res) $this->result('清空购物车成功', [],200,'json');
          $this->result('清空购物车失败', [],403,'json');
       }
       //立即结算
       public function settlement(){
            $post = $this->request::param();
            $carts=Db::name('cart')->whereIn('id',$post['cart_ids'])->select()->toArray();
            $out_trade_no = orderNumber();
            $price=0;
            $deposit=0;
            $spec='';
            $amount=0;
            foreach ($carts as $k => $v) {
                if($v['type']==2){
                      $lease=Db::name('lease')->where('id',$v['server_id'])->find();
                      $deposit+=$lease['deposit']*$v['number'];
                      $amount=$lease['deposit'];
                  }elseif($v['type']==3){
                    $spec=$v['spec'];
                  } 
                  $order_server[$k]['amount']=$amount;
                  $order_server[$k]['house_num']=$v['house_num'];
                  $order_server[$k]['house_title']=$v['house_title'];
                  $order_server[$k]['time_id']=$v['time_id'];
                  $order_server[$k]['spec']=$spec;
                  $order_server[$k]['number']=$v['number'];
                  $order_server[$k]['server_id']=$v['server_id'];
                  $order_server[$k]['type']=$v['type'];
                  $order_server[$k]['price']=$v['price'];
                  $order_server[$k]['act_price']=$v['activity_price'];   
                  $price+=$v['activity_price']*$v['number'];  
               
            $amount=0;     
            }  
            Db::startTrans();
            try{
                    $order['out_trade_no'] = $out_trade_no;
                    $order['members_id'] = $this->user_member_id;
                    $order['orders_status'] = 0;
                    $order['use_time'] =$post['use_time']?strtotime(date('Y-').$post['use_time']):strtotime(date('Y-m-d'));
                    $order['create_time'] =time();
                    $order['price'] =$price;
                    $order['amount'] =$deposit;
                    $order['users']=$this->user_member_id; 
                $order_id=Db::name('order') -> insertGetId($order);
                foreach ($order_server as $k => $v) {
                   $order_server[$k]['order_id']=$order_id;
                }
                Db::name('order_server')->insertAll($order_server);
                Db::name('cart')->whereIn('id',$post['cart_ids'])->where('members_id',$this->user_member_id)->delete();
                Db::commit();
                $this->result('下单成功',['out_trade_no'=>$out_trade_no,'order_id'=>$order_id],200);
            }catch(Exception $e){
                Db::rollback();
                $this->result($e->getMessage(),[],403);

            }
       }
}
